#include "GPIOManager.h"

#include <stdlib.h>

#define MODE_FILE_FORMAT "/sys/devices/virtual/misc/gpio/mode/gpio%d"
#define PIN_FILE_FORMAT  "/sys/devices/virtual/misc/gpio/pin/gpio%d"


FILE* openGpioModeFile(int numPin)
{
	char buffer[128];
	sprintf(buffer, MODE_FILE_FORMAT, numPin);
	return fopen(buffer,"w");
}

FILE* openGpioPinFile(int numPin, char* mode)
{
	char buffer[128];
	sprintf(buffer, PIN_FILE_FORMAT, numPin);
	return fopen(buffer, mode);
}

int pinMode(FILE* modeFile, char* mode)
{
	if( modeFile == NULL )
	{
		fprintf(stderr,"File is undefined\n");
		return -1;
	}
	
	/* Set the pin to be an output or intput pin */
	if( fwrite(mode, 1, 1, modeFile) == 0 )
	{
		fprintf(stderr,"Unable to write into mode file\n");
		return -1;
	}

	return 1;
}

int pinWrite(FILE* pinFile, char* mode)
{
	if(pinFile == NULL)
	{
		fprintf(stderr,"File is undefined\n\n");
		return -1;
	}
	
	/* Set the pin to OFF or ON */
	if( fwrite(mode, 1, 1, pinFile) == 0 )
	{
		fprintf(stderr,"Unable to write into mode file\n");
		return -1;
	}
	
	/* Force to write into the file */
	fflush(pinFile);
	
	return 1;
}

int pinRead(FILE* pinFile)
{
	char buffer[4];
	
	if(pinFile == NULL)
	{
		fprintf(stderr, "File is undefined\n");
		return -1;
	}
	
	if( fread(buffer, 1, 4, pinFile) <= 0) 
	{
		fprintf(stderr,"Error on read\n");
		return -1;
	}
	
	return atoi(buffer);
}
